package com.aahackathon.tripme;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

import com.aahackathon.tripme.model.SearchOptions;
import com.aahackathon.tripme.model.Trip;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;


public class MyActivity extends Activity {

    public static final String WS = "http://tripme.azurewebsites.net/api/TripFinder/GetFlightData?";
    //<editor-fold desc="Members">
    private EditText mOrigin;
    private EditText mPaxCount;
    private EditText mMaxPrice;
    private EditText mFlightDuration;
    private RadioButton mDayTrip;
    private Button mTripMe;
    public static final DateFormat FULL_DATE = new SimpleDateFormat(
            "yyyy-MM-dd'T'HH:mm");
    //</editor-fold>

    //<editor-fold desc="Overrides">
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);

        mOrigin = (EditText) findViewById(R.id.activity_my_origin);
        mPaxCount = (EditText) findViewById(R.id.activity_my_pax_count);
        mMaxPrice = (EditText) findViewById(R.id.activity_my_max_price);
        mFlightDuration = (EditText) findViewById(R.id.activity_my_duration);
        mDayTrip = (RadioButton) findViewById(R.id.activity_my_day_trip);
        mTripMe = (Button) findViewById(R.id.activity_my_search);
        mTripMe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                search();
            }
        });
    }

    //</editor-fold>

    //<editor-fold desc="Private Methods">
    private void search() {
        final SearchOptions so = new SearchOptions();
        try {
            so.setOrigin(mOrigin.getText().toString());
            so.setFlightDuration(Integer.parseInt(mFlightDuration.getText().toString()));
            so.setMaxPrice(Integer.valueOf(mMaxPrice.getText().toString()));
            so.setIsDayTrip(mDayTrip.isChecked());
            so.setPaxCount(Integer.valueOf(mPaxCount.getText().toString()));
            new AsyncTask<SearchOptions, Void, ArrayList<Trip>>() {

                Exception e;
                String resultToDisplay = "";
                InputStream in = null;

                @Override
                protected ArrayList<Trip> doInBackground(SearchOptions... searchOptions) {
                    ArrayList<Trip> trips = new ArrayList<Trip>();
                    try {
                        StringBuilder builder = new StringBuilder();
                        HttpClient client = new DefaultHttpClient();
                        HttpGet httpGet = new HttpGet(BuildURL(so));
                        HttpResponse response = client.execute(httpGet);
                        StatusLine statusLine = response.getStatusLine();
                        int statusCode = statusLine.getStatusCode();
                        if (statusCode == 200) {
                            HttpEntity entity = response.getEntity();
                            InputStream content = entity.getContent();
                            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                            String line;
                            while ((line = reader.readLine()) != null) {
                                builder.append(line);
                            }
                        } else {
                            Log.e("TripMe", "Failed to download file");
                        }

                        JSONArray json = new JSONArray(builder.toString());
                        for (int i = 0; i < json.length(); i++) {
                            JSONObject obj = json.getJSONObject(i);
                            Trip trip = new Trip();
                            trip.setFlightNumber(obj.getInt("OriginFlightNumber"));
                            trip.setInboundFlightNumber(obj.getInt("DestinationFlightNumber"));
                            trip.setOrigin(obj.getString("OriginAirportCode"));
                            trip.setDestination(obj.getString("DestinationAirportCode"));
                            trip.setOriginDeparture(FULL_DATE.parse(obj.getString("OriginDepartTime")));
                            trip.setOriginArrival(FULL_DATE.parse(obj.getString("OriginArrivalTime")));
                            trip.setDestinationDeparture(FULL_DATE.parse(obj.getString("DestinationDepartTime")));
                            trip.setDestinationArrival(FULL_DATE.parse(obj.getString("DestinationArrivalTime")));
                            trip.setPrice(obj.getDouble("Price"));
                            trips.add(trip);
                        }
                    } catch (Exception ex) {
                        e = ex;
                    }
                    return trips;
                }

                @Override
                protected void onPostExecute(ArrayList<Trip> trips) {
                    if (e != null) {
                        Toast.makeText(MyActivity.this, "Error getting trips: " + e.getMessage(), Toast.LENGTH_LONG).show();
                        Log.e("TripMe", e.toString());
                        return;
                    }
                    Intent i = new Intent(MyActivity.this, TripList.class);
                    i.putExtra(TripList.FLIGHT_LIST, trips);
                    startActivity(i);
                }
            }.execute(so);

        } catch (Exception ex) {
            Toast.makeText(MyActivity.this, "Error parsing options: " + ex.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    private String BuildURL(SearchOptions so) {
        return WS
                + "departCityCode=" + so.getOrigin()
                + "&maxPrice=" + so.getMaxPrice()
                + "&paxCount=" + so.getPaxCount()
                + "&fltDurationMinutes=" + so.getFlightDuration()
                + "&dayStay=" + (so.isDayTrip() ? "1" : "2");
    }
    //</editor-fold>

}
